#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
关键词管理模块

管理监控关键词、负面词汇库、品牌词汇等。
"""

import json
import os
import logging
from typing import Dict, List, Set, Optional
from datetime import datetime

class KeywordManager:
    """关键词管理器"""
    
    def __init__(self, config_dir: str = None):
        self.logger = logging.getLogger(__name__)
        
        if config_dir is None:
            config_dir = os.path.join(os.path.dirname(__file__), "keywords")
        
        self.config_dir = config_dir
        self.keywords_file = os.path.join(config_dir, "keywords.json")
        
        # 确保目录存在
        os.makedirs(config_dir, exist_ok=True)
        
        # 初始化关键词数据
        self.keywords_data = self._load_keywords()
        
        self.logger.info(f"关键词管理器初始化完成，配置目录: {config_dir}")
    
    def _load_keywords(self) -> Dict:
        """加载关键词配置"""
        if os.path.exists(self.keywords_file):
            try:
                with open(self.keywords_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                self.logger.info(f"已加载关键词配置文件: {self.keywords_file}")
                return data
            except Exception as e:
                self.logger.error(f"加载关键词配置文件失败: {e}")
        
        # 返回默认配置
        default_data = self._get_default_keywords()
        self._save_keywords(default_data)
        return default_data
    
    def _get_default_keywords(self) -> Dict:
        """获取默认关键词配置"""
        return {
            "version": "1.0.0",
            "last_updated": datetime.now().isoformat(),
            
            # 监控目标关键词
            "monitor_keywords": {
                "brands": [],  # 品牌词汇
                "products": [],  # 产品名称
                "competitors": [],  # 竞争对手
                "custom": []  # 自定义关键词
            },
            
            # 负面词汇库
            "negative_keywords": {
                "quality": [  # 质量问题
                    "难吃", "恶心", "垃圾", "差劲", "糟糕", "烂", "臭", "坏",
                    "不好吃", "太难吃", "超难吃", "巨难吃", "口感差", "味道怪"
                ],
                "service": [  # 服务问题
                    "态度差", "服务差", "冷漠", "傲慢", "无礼", "粗鲁",
                    "不耐烦", "爱理不理", "黑脸", "服务员差", "没素质"
                ],
                "environment": [  # 环境问题
                    "脏", "乱", "差", "嘈杂", "吵", "臭味", "异味",
                    "不卫生", "太脏", "环境差", "装修差", "破旧"
                ],
                "price": [  # 价格问题
                    "坑人", "宰客", "黑店", "天价", "太贵", "不值",
                    "性价比低", "不划算", "坑钱", "贵得离谱", "价格虚高"
                ],
                "serious": [  # 严重问题
                    "食物中毒", "拉肚子", "吃坏肚子", "有虫子", "有头发",
                    "过期", "变质", "发霉", "有异物", "不新鲜", "有问题"
                ],
                "emotion": [  # 负面情绪
                    "愤怒", "气愤", "生气", "郁闷", "失望", "后悔",
                    "不推荐", "别去", "千万别", "劝退", "坑死了"
                ]
            },
            
            # 正面词汇库
            "positive_keywords": {
                "taste": [  # 味道好
                    "好吃", "美味", "香", "鲜", "甜", "爽", "嫩", "酥",
                    "太好吃", "超好吃", "巨好吃", "很香", "很鲜", "口感好"
                ],
                "service": [  # 服务好
                    "服务好", "态度好", "热情", "周到", "贴心", "专业",
                    "有耐心", "很客气", "笑容满面", "服务员好", "有礼貌"
                ],
                "environment": [  # 环境好
                    "干净", "整洁", "舒适", "优雅", "温馨", "安静",
                    "环境好", "装修好", "氛围好", "很干净", "很舒适"
                ],
                "price": [  # 价格好
                    "便宜", "实惠", "划算", "性价比高", "物美价廉",
                    "良心价", "不贵", "合理", "超值", "值得"
                ],
                "recommendation": [  # 推荐
                    "推荐", "值得", "不错", "很好", "棒", "赞", "满意",
                    "会再来", "还会来", "必须点赞", "强烈推荐", "五星推荐"
                ]
            },
            
            # 程度副词
            "degree_modifiers": {
                "strong": ["极", "超", "特别", "非常", "太", "巨", "贼", "老"],
                "medium": ["很", "比较", "还", "挺"],
                "weak": ["稍微", "有点", "略微", "还算"]
            },
            
            # 否定词
            "negation_words": ["不", "没", "无", "非", "未", "别", "莫", "勿", "从不", "绝不"],
            
            # 排除词汇（不参与情感分析的词）
            "exclude_words": ["的", "了", "是", "在", "有", "和", "我", "你", "他", "她", "它"]
        }
    
    def _save_keywords(self, data: Dict) -> bool:
        """保存关键词配置"""
        try:
            data["last_updated"] = datetime.now().isoformat()
            with open(self.keywords_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            self.logger.info("关键词配置已保存")
            return True
        except Exception as e:
            self.logger.error(f"保存关键词配置失败: {e}")
            return False
    
    def add_monitor_keyword(self, keyword: str, category: str = "custom") -> bool:
        """添加监控关键词"""
        if category not in self.keywords_data["monitor_keywords"]:
            self.keywords_data["monitor_keywords"][category] = []
        
        if keyword not in self.keywords_data["monitor_keywords"][category]:
            self.keywords_data["monitor_keywords"][category].append(keyword)
            self._save_keywords(self.keywords_data)
            self.logger.info(f"已添加监控关键词: {keyword} ({category})")
            return True
        
        return False
    
    def remove_monitor_keyword(self, keyword: str, category: str = None) -> bool:
        """移除监控关键词"""
        removed = False
        
        if category:
            # 从指定类别移除
            if (category in self.keywords_data["monitor_keywords"] and 
                keyword in self.keywords_data["monitor_keywords"][category]):
                self.keywords_data["monitor_keywords"][category].remove(keyword)
                removed = True
        else:
            # 从所有类别移除
            for cat, keywords in self.keywords_data["monitor_keywords"].items():
                if keyword in keywords:
                    keywords.remove(keyword)
                    removed = True
        
        if removed:
            self._save_keywords(self.keywords_data)
            self.logger.info(f"已移除监控关键词: {keyword}")
        
        return removed
    
    def get_monitor_keywords(self, category: str = None) -> List[str]:
        """获取监控关键词"""
        if category:
            return self.keywords_data["monitor_keywords"].get(category, [])
        
        # 返回所有监控关键词
        all_keywords = []
        for keywords in self.keywords_data["monitor_keywords"].values():
            all_keywords.extend(keywords)
        
        return list(set(all_keywords))  # 去重
    
    def add_negative_keyword(self, keyword: str, category: str = "custom") -> bool:
        """添加负面关键词"""
        if category not in self.keywords_data["negative_keywords"]:
            self.keywords_data["negative_keywords"][category] = []
        
        if keyword not in self.keywords_data["negative_keywords"][category]:
            self.keywords_data["negative_keywords"][category].append(keyword)
            self._save_keywords(self.keywords_data)
            self.logger.info(f"已添加负面关键词: {keyword} ({category})")
            return True
        
        return False
    
    def get_negative_keywords(self, category: str = None) -> List[str]:
        """获取负面关键词"""
        if category:
            return self.keywords_data["negative_keywords"].get(category, [])
        
        # 返回所有负面关键词
        all_keywords = []
        for keywords in self.keywords_data["negative_keywords"].values():
            all_keywords.extend(keywords)
        
        return list(set(all_keywords))  # 去重
    
    def get_positive_keywords(self, category: str = None) -> List[str]:
        """获取正面关键词"""
        if category:
            return self.keywords_data["positive_keywords"].get(category, [])
        
        # 返回所有正面关键词
        all_keywords = []
        for keywords in self.keywords_data["positive_keywords"].values():
            all_keywords.extend(keywords)
        
        return list(set(all_keywords))  # 去重
    
    def get_degree_modifiers(self) -> Dict[str, List[str]]:
        """获取程度副词"""
        return self.keywords_data.get("degree_modifiers", {})
    
    def get_negation_words(self) -> List[str]:
        """获取否定词"""
        return self.keywords_data.get("negation_words", [])
    
    def is_monitor_keyword_matched(self, text: str) -> List[Dict]:
        """检查文本是否匹配监控关键词"""
        matches = []
        all_keywords = self.get_monitor_keywords()
        
        for keyword in all_keywords:
            if keyword.lower() in text.lower():
                # 找到匹配的类别
                category = None
                for cat, keywords in self.keywords_data["monitor_keywords"].items():
                    if keyword in keywords:
                        category = cat
                        break
                
                matches.append({
                    "keyword": keyword,
                    "category": category,
                    "position": text.lower().find(keyword.lower())
                })
        
        return matches
    
    def export_keywords(self, filepath: str) -> bool:
        """导出关键词配置"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(self.keywords_data, f, ensure_ascii=False, indent=2)
            self.logger.info(f"关键词配置已导出到: {filepath}")
            return True
        except Exception as e:
            self.logger.error(f"导出关键词配置失败: {e}")
            return False
    
    def import_keywords(self, filepath: str) -> bool:
        """导入关键词配置"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                imported_data = json.load(f)
            
            # 验证数据格式
            required_keys = ["monitor_keywords", "negative_keywords", "positive_keywords"]
            for key in required_keys:
                if key not in imported_data:
                    raise ValueError(f"缺少必需的配置项: {key}")
            
            # 合并数据
            self._merge_keywords_data(imported_data)
            self._save_keywords(self.keywords_data)
            
            self.logger.info(f"关键词配置已从 {filepath} 导入")
            return True
        except Exception as e:
            self.logger.error(f"导入关键词配置失败: {e}")
            return False
    
    def _merge_keywords_data(self, imported_data: Dict):
        """合并关键词数据"""
        for main_key in ["monitor_keywords", "negative_keywords", "positive_keywords"]:
            if main_key in imported_data:
                for category, keywords in imported_data[main_key].items():
                    if category not in self.keywords_data[main_key]:
                        self.keywords_data[main_key][category] = []
                    
                    # 合并关键词列表，去重
                    existing = set(self.keywords_data[main_key][category])
                    new_keywords = set(keywords)
                    self.keywords_data[main_key][category] = list(existing.union(new_keywords))
    
    def get_statistics(self) -> Dict:
        """获取关键词统计信息"""
        stats = {
            "monitor_keywords": {},
            "negative_keywords": {},
            "positive_keywords": {},
            "total_monitor": 0,
            "total_negative": 0,
            "total_positive": 0
        }
        
        # 统计监控关键词
        for category, keywords in self.keywords_data["monitor_keywords"].items():
            count = len(keywords)
            stats["monitor_keywords"][category] = count
            stats["total_monitor"] += count
        
        # 统计负面关键词
        for category, keywords in self.keywords_data["negative_keywords"].items():
            count = len(keywords)
            stats["negative_keywords"][category] = count
            stats["total_negative"] += count
        
        # 统计正面关键词
        for category, keywords in self.keywords_data["positive_keywords"].items():
            count = len(keywords)
            stats["positive_keywords"][category] = count
            stats["total_positive"] += count
        
        return stats
    
    def validate_keywords(self) -> Dict:
        """验证关键词配置"""
        issues = []
        
        # 检查是否有空的关键词
        for main_key in ["monitor_keywords", "negative_keywords", "positive_keywords"]:
            for category, keywords in self.keywords_data[main_key].items():
                empty_keywords = [k for k in keywords if not k or not k.strip()]
                if empty_keywords:
                    issues.append(f"{main_key}.{category} 包含空关键词")
        
        # 检查重复关键词
        all_negative = set()
        for keywords in self.keywords_data["negative_keywords"].values():
            for keyword in keywords:
                if keyword in all_negative:
                    issues.append(f"负面关键词重复: {keyword}")
                all_negative.add(keyword)
        
        return {
            "valid": len(issues) == 0,
            "issues": issues,
            "total_issues": len(issues)
        }
    
    def refresh(self):
        """重新加载关键词配置"""
        self.keywords_data = self._load_keywords()
        self.logger.info("关键词配置已刷新")